package com.pomelo.base.core.util;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.math.NumberUtils;

import cn.hutool.core.util.URLUtil;

/**
 * 字符串
 *
 * @author biankudingcha
 * @date: 2021-09-26
 * @since 0.5.0
 */
public class StringUtil {

    /**
     * 使用指定分隔符连接数组元素
     */
    public static String join(String[] arr, String sep) {
        if (arr == null || arr.length < 1) {
            return "";
        }
        return org.apache.commons.lang3.StringUtils.join(arr, sep);
    }

    /**
     * 使用指定分隔符连接集合元素
     */
    public static String join(List<Object> list, String sep) {
        if (list == null || list.size() < 1) {
            return sep + sep;
        }
        List<String> datas = new ArrayList<String>();
        for (int i = 0; i < list.size(); i++) {
            String data = list.get(i) == null ? null : list.get(i).toString();
            datas.add(data);
        }
        return join(datas.toArray(new String[0]), sep);
    }

    public static boolean isEmpty(Object str) {
        return (str == null || "".equals(str));
    }

    public static String toStr(Object o) {
        return o == null ? "" : o.toString();
    }

    public static String toStr(Object o, String defaultValue) {
        return o == null || o.toString().equals("") ? defaultValue : o.toString();
    }

    public static int toInt(Object o) {
        return NumberUtils.toInt(o == null ? null : o.toString(), 0);
    }

    public static int toInt(Object o, int defaultValue) {
        return o == null || o.toString().equals("") ? defaultValue : NumberUtils.toInt(o.toString(), 0);
    }

    public static long toLong(Object o) {
        return NumberUtils.toLong(o == null ? null : o.toString(), 0);
    }

    public static long toLong(Object o, long defaultValue) {
        return o == null ? defaultValue : NumberUtils.toLong(o.toString(), 0);
    }

    public static String nvl(String o) {
        return o == null ? "" : o.trim();
    }

    public static boolean isNumber(String o) {
        return NumberUtils.isCreatable(o);
    }

    public static String urlDecode(Object url) {
        return URLUtil.decode(toStr(url));
    }

    public static String urlEncode(Object url) {
        return URLUtil.encode(toStr(url));
    }
}
